import * as pdfjsLib from 'pdfjs-dist';

// 配置 Worker（必须）
pdfjsLib.GlobalWorkerOptions.workerSrc = import.meta.env.BASE_URL + 'pdf.js'

/**
 * 将PDF合并为一张长图
 * @param {String|Uint8Array} pdfSource - PDF文件路径或二进制数据
 * @param {Object} [options] - 配置选项
 * @param {Number} [options.scale=1.5] - 缩放比例
 * @param {String} [options.imageType='image/png'] - 输出图片格式
 * @param {Number} [options.imageQuality=0.92] - 图片质量(0-1)
 * @param {Function} [options.onProgress] - 进度回调(currentPage, totalPages)
 * @returns {Promise<String>} - 返回Base64图片数据
 */
export async function mergePdfToImage(pdfSource, options = {}) {
    const {
        scale = 1.5,
        imageType = 'image/png',
        imageQuality = 0.92,
        onProgress
    } = options;

    let pdf;
    try {
        // 1. 加载PDF
        const loadingTask = pdfjsLib.getDocument({
            url: typeof pdfSource === 'string' ? pdfSource : undefined,
            data: typeof pdfSource !== 'string' ? pdfSource : undefined,
            cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.9.359/cmaps/',
            cMapPacked: true,
        });
        pdf = await loadingTask.promise;
        onProgress?.(0, pdf.numPages);

        // 2. 预计算尺寸
        let totalHeight = 0;
        let maxWidth = 0;
        const pageData = [];

        for (let i = 1; i <= pdf.numPages; i++) {
            const page = await pdf.getPage(i);
            const viewport = page.getViewport({ scale });
            pageData.push({ page, viewport });
            totalHeight += viewport.height;
            maxWidth = Math.max(maxWidth, viewport.width);
            page.cleanup();
            onProgress?.(i, pdf.numPages);
        }

        // 3. 创建主Canvas
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = maxWidth;
        canvas.height = totalHeight;

        // 填充背景（避免透明）
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 4. 逐页渲染
        let yOffset = 0;
        for (let i = 0; i < pageData.length; i++) {
            const { page, viewport } = pageData[i];
            const renderPage = await pdf.getPage(page.pageNumber);

            // 使用临时Canvas
            const tempCanvas = document.createElement('canvas');
            tempCanvas.width = viewport.width;
            tempCanvas.height = viewport.height;
            const tempCtx = tempCanvas.getContext('2d');

            await renderPage.render({
                canvasContext: tempCtx,
                viewport: viewport,
                background: 'rgba(255,255,255,1)'
            }).promise;

            // 绘制到主Canvas
            ctx.drawImage(tempCanvas, 0, yOffset);
            yOffset += viewport.height;

            renderPage.cleanup();
            onProgress?.(i + 1, pdf.numPages);

            // 避免阻塞UI
            if (i % 3 === 0) await new Promise(r => requestAnimationFrame(r));
        }

        // 5. 生成图片
        return canvas.toDataURL(imageType, imageQuality);

    } catch (error) {
        console.error('[PDF合并错误]', error);
        throw error;
    } finally {
        pdf?.destroy();
    }
}